(function(global) {
var APP = global.APP, 
	Spine = global.Spine, 
	$ = global.$;

var _STATES = APP._classes.states,
	Dialog = APP.require('Modules.Dialog'),
	FormHandler = APP.require('Modules.FormHandler');

var Admin = Spine.Controller.sub($.extend({}, APP.Template, APP.Message, APP.Cache, APP.MouseHandler), APP.Registry);
Admin.elements = {
	".ui-button" : "$button",
	".container" : "$container"
};
Admin.events = {
	"mouseenter [data-action]" : "highlight",
	"mouseleave [data-action]" : "highlight",
	"click [data-action]" : "click"
};
Admin.prototype.init = function() {
	APP.css('Katsu.Modules.Admin');
	this.$button.addClass(_STATES.base);

	this.bind('click', this.proxy(this.action));
	this.afterInit();
};
Admin.prototype.render = function(model, items, template) {
	var $container = this.$container.filter('[data-model="' + model + '"]');
		func = this.models && this.models[model] && this.models[model].sort;

		if (typeof func === 'undefined') {
			func = function(a, b) { return a.name.toLowerCase() > b.name.toLowerCase() };
		}

	if (items.length > 0 && typeof func === 'function') {
		items.sort(func);
	}
	this.tmplAll($container, items);
};
Admin.prototype.redirect = function(model, action, params) {
	var url = (this.models && this.models[model] && this.models[model][action]) ? this.models[model][action].interpolate(params) : action;
	window.location = url;
};
Admin.prototype.form = function(model, action, params, title) {
	var _urls = this.models[model], 
		Model = this.registry(model),
		url = _urls[action] || action,
		dialog, form, self = this;

	if (this.cache('dialog')) {
		return;
	}
	url = url.interpolate(params);
	dialog = new Dialog({ 
		url : url,
		title : title || action.humanize() + ' ' + Model.className
	});
	dialog.bind('close', function() {
		self.cache('dialog', false);
		self.cache('form').destroy();
	});
	dialog.bind('open', function($dialog) {
		form = new FormHandler({ el : $dialog.find('form') });
		form.bind('success', function(response) {
			var data = response.data, message = response.message, method = response.method, redirect = response.redirect;

			if (redirect) {
				window.location = redirect;
				return;
			}

			if (response.method === 'POST') {
				Model.create(data);
			} else {
				Model.update(data.id, data);
			}
			if (self.success) {
				self.success(Model.className, data.id, response);
			}
			self.message(message);
			self.cache('dialog').close();
		});
		self.cache('form', form);
	});
	dialog.open();
	this.cache('dialog', dialog);
};


APP.namespace('Modules.Admin', Admin);
}) (this);